/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package view;

import com.sun.lwuit.Command;
import com.sun.lwuit.Label;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.layouts.BoxLayout;
import core.IMAPMIDlet;
import core.OrderManager;
import core.ScreenEngine;
import datamodel.Message;
import datamodel.Order;
import view.additional.CellItem;
import view.additional.MenuList;
import view.commands.BackCommand;

/**
 *
 * @author Kvest
 */
public class OrderFunctionsForm extends BasicForm implements MenuList.MenuListSelection
{
    private static final int OK_COMMAND_ID = 1;
    
    private static final int LATE_ITEM_ID = 0;
    private static final int ON_ADDRESS_ITEM_ID = 1; //CALL_PASS_ID
    private static final int PASSENGER_OUT_ITEM_ID = 2; //NOT_EXIT_ID
    private static final int STANDING_ITEM_ID = 3; //?
    private static final int WITH_PASSENGER_ITEM_ID = 4;
    private static final int CLOSE_ORDER_ITEM_ID = 5;
    private static final int REFUSE_ORDER_ITEM_ID = 6;
    private static final int CURR_ORDER_INFO_ITEM_ID = 7;
    private static final int CONNECT_TO_CLIENT = 8;
    
    private TimeSelectForm lateTimeSelectForm;
    private TimeSelectForm passengerOutTimeSelectForm;
    
    private MenuList items;
    private CellItem lateItem;
    private CellItem onAddressItem;
    private CellItem passengerOutItem;
    private CellItem standItem;
    private CellItem withPassengerItem;
    private CellItem closeOrderItem;
    private CellItem refuseOrderItem;
    private CellItem currOrderInfoItem;
    private CellItem connectToClient; 
    
    private OrderManager orderManager;
    private OrderForm orderForm;
    
    public OrderFunctionsForm()
    {
        super("order");
        
        orderManager = IMAPMIDlet.getMidlet().getOrderManager();
        
        init();
    }
    
    private void init()
    {
        setLayout(new BoxLayout(BoxLayout.Y_AXIS));
        setScrollable(false);
        
        items = new MenuList();
        lateItem = new CellItem(LATE_ITEM_ID, "late");
        items.addItem(lateItem);
        onAddressItem = new CellItem(ON_ADDRESS_ITEM_ID, "on_address");
        items.addItem(onAddressItem);
        passengerOutItem = new CellItem(PASSENGER_OUT_ITEM_ID, "passenger_out");
        items.addItem(passengerOutItem);
        standItem = new CellItem(STANDING_ITEM_ID, "standing");
        items.addItem(standItem);
        withPassengerItem = new CellItem(WITH_PASSENGER_ITEM_ID, "with_passenger");
        items.addItem(withPassengerItem);
        connectToClient = new CellItem(CONNECT_TO_CLIENT, "connect_to_client");
        items.addItem(connectToClient);
        closeOrderItem = new CellItem(CLOSE_ORDER_ITEM_ID, "close_order");
        items.addItem(closeOrderItem);
        refuseOrderItem = new CellItem(REFUSE_ORDER_ITEM_ID, "refuse_order");
        items.addItem(refuseOrderItem);
        currOrderInfoItem = new CellItem(CURR_ORDER_INFO_ITEM_ID, "curr_order_info");
        items.addItem(currOrderInfoItem);
        items.setSelectionListener(this);
        addComponent(items);
        
        //Команды
        addCommand(new BackCommand());
        
        Command ok = new Command("ok", OK_COMMAND_ID)
        {
            public void actionPerformed(ActionEvent evt)
            {
                itemSelected(items.getSelectedId());
                
                evt.consume();
            }
        };
        addCommand(ok);
    }
    
    public void show()
    {
        //Устанавливаем активные\неактивные пункты
        setItemsState();
        
        super.show();
    }
    
    public void itemSelected(int id)
    {
        switch(id)
        {
            case LATE_ITEM_ID : showLateTimeSelectForm(); break;
            case ON_ADDRESS_ITEM_ID : sendOnAddressRequest(); break;
            case PASSENGER_OUT_ITEM_ID : passengerOutAction(); break; 
            case STANDING_ITEM_ID : showPassengerOutTimeSelectForm(); break; 
            case WITH_PASSENGER_ITEM_ID : sendWithPassengerResuest(); break; 
            case CLOSE_ORDER_ITEM_ID : sendCloseOrderRequest(); break;
            case REFUSE_ORDER_ITEM_ID : sendRefuseOrderRequest(); break;
            case CURR_ORDER_INFO_ITEM_ID : showCurrentOrder(); break;
            case CONNECT_TO_CLIENT : sendConnectToClientRequest();break;
        }
    }
    
    private void setItemsState()
    {
        lateItem.setEnabled(state == CONNECTED_STATE);
        onAddressItem.setEnabled(state == CONNECTED_STATE);
        passengerOutItem.setEnabled(state == CONNECTED_STATE);
        standItem.setEnabled(state == CONNECTED_STATE);
        withPassengerItem.setEnabled(state == CONNECTED_STATE);
        closeOrderItem.setEnabled(state == CONNECTED_STATE);
        refuseOrderItem.setEnabled(state == CONNECTED_STATE);
        currOrderInfoItem.setEnabled(state == CONNECTED_STATE);
        connectToClient.setEnabled(state == CONNECTED_STATE);
    }
    
    private void showLateTimeSelectForm()
    {
        if (lateTimeSelectForm == null)
        {
            lateTimeSelectForm = new TimeSelectForm("late", new TimeSelectForm.TimeSelected() 
            {
                public void timeSelected(int time) 
                {
                    //Возвращаемся на главную форму
                    ScreenEngine.getEngine().popTo(0);
                    
                    if (orderManager.currentOrder() != OrderManager.NO_ORDER_ID)
                    {
                        //Отправляем запрос на опоздание
                        orderManager.sendLateRequest(time);
                    }
                    else 
                    {
                        showNoOrderMessage();
                    }
                }
            });
        }
        
        ScreenEngine.getEngine().push(lateTimeSelectForm);
    }
    
    private void sendOnAddressRequest()
    {
        //Возвращаемся на главную форму
        ScreenEngine.getEngine().popTo(0);
        
        if (orderManager.currentOrder() != OrderManager.NO_ORDER_ID)
        {
            //Отправляем запрос
            orderManager.sendCarOnAddressRequest();
        }
        else 
        {
            showNoOrderMessage();
        }
    }
    
    private void passengerOutAction()
    {
        //Возвращаемся на главную форму
        ScreenEngine.getEngine().popTo(0);
        
        if (orderManager.currentOrder() != OrderManager.NO_ORDER_ID)
        {
            //Отправляем запрос
            orderManager.sendPassengerOutRequest(0);
        }
        else 
        {
            showNoOrderMessage();
        }
    }
    
    private void sendConnectToClientRequest() {
        //Возвращаемся на главную форму
        ScreenEngine.getEngine().popTo(0);
        
        if (orderManager.currentOrder() != OrderManager.NO_ORDER_ID) {
            //Отправляем запрос
            orderManager.connectToClient();
            //Показываем сообщение
            showRequestSentMessage();
        } else {
            showNoOrderMessage();
        }
    }
    
    private void showPassengerOutTimeSelectForm()
    {
        if (passengerOutTimeSelectForm == null)
        {
            passengerOutTimeSelectForm = new TimeSelectForm("standing", new TimeSelectForm.TimeSelected() 
            {
                public void timeSelected(int time) 
                {
                    //Возвращаемся на главную форму
                    ScreenEngine.getEngine().popTo(0);
                    
                    if (orderManager.currentOrder() != OrderManager.NO_ORDER_ID)
                    {
                        //Отправляем запрос на опоздание
                        orderManager.sendPassengerOutRequest(time);
                    }
                    else 
                    {
                        showNoOrderMessage();
                    }
                }
            });
        }
        
        ScreenEngine.getEngine().push(passengerOutTimeSelectForm);
    }
    
    private void sendWithPassengerResuest()
    {
        //Возвращаемся на главную форму
        ScreenEngine.getEngine().popTo(0);
        
        if (orderManager.currentOrder() != OrderManager.NO_ORDER_ID)
        {
            //Отправляем запрос
            orderManager.sendWithPassengerRequest();
        }
        else 
        {
            showNoOrderMessage();
        }
    }
    
     private void sendCloseOrderRequest()
     {
        //Возвращаемся на главную форму
        ScreenEngine.getEngine().popTo(0);
        
        if (orderManager.currentOrder() != OrderManager.NO_ORDER_ID)
        {
            //Определяем можем ли мы закрыть заказа
            boolean canCloseOrder = true;
            if (!IMAPMIDlet.getMidlet().getRuntimeData().isCheckNoSubOrderForClose()) {            
                Order order = orderManager.getCurrentOrder();
                if (order != null) {                    
//                    canCloseOrder = (order.hasSuborders() || order.isWithSum());
                    canCloseOrder = (order.hasSuborders() || order.isWithSum());
                    if (!order.hasSuborders()) {
                        canCloseOrder = false;
                    }
                    
//                    заказ без подзаказов = !order.hasSuborders()
//                            !order.isWithSum()
//                    если заказ без подзаказов ИЛИ заказ С подзаказом "без суммы", то не давать закрывать?
                }
            }                                
             
            if (canCloseOrder) {
                //Отправляем запрос
                orderManager.sendCloseOrderRequest();
            } else {
                //Выводим сообщение
                ScreenEngine.getEngine().showMessageBox("error", (new Label("cant_close_order")).getText(), -1);
            }
        }
        else 
        {
            showNoOrderMessage();
        }
     }
     
     private void sendRefuseOrderRequest()
     {
        //Возвращаемся на главную форму
        ScreenEngine.getEngine().popTo(0);
        
        if (orderManager.currentOrder() != OrderManager.NO_ORDER_ID)
        {
            //Отправляем запрос
            orderManager.sendRefuseOrderRequest();
        }
        else 
        {
            showNoOrderMessage();
        }
     }
     
     private void showCurrentOrder()
     {
        //Находим текущий заказ
        Order currentOrder = orderManager.getCurrentOrder();
        if (currentOrder != null)
        {
            showOrder(currentOrder);
        }
        else
        {
            showNoOrderMessage();
        }
     }
     
     private void showOrder(Order order)
     {
        if (orderForm == null)
        {
            orderForm = new OrderForm("curr_order_info");
        }
        
        orderForm.setOrder(order);
        ScreenEngine.getEngine().push(orderForm);
     }
     
     private void showNoOrderMessage()
     {
        Message message = new Message((new Label("no_current_orders")).getText()); 
        message.setTimeout(10000);
        IMAPMIDlet.getMidlet().getMessageManager().newMessage(message);
     }
     
     private void showRequestSentMessage() {
        Message message = new Message((new Label("request_sent")).getText());
        message.setTimeout(10000);
        IMAPMIDlet.getMidlet().getMessageManager().newMessage(message);
     }
}
